import React, {Component} from 'react';
import {SingleFigure} from '@/components/Chart/Figure';
import { getQueryString } from '@/utils/util';
import {getDeviceOutdoorFireHydrantCurrent} from '../service';

function flatten(arr, result = []) {
  for (let item of arr) {
      if (Array.isArray(item))
          flatten(item, result)
      else
          result.push(item)
  }
  return result
}

const groupBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
    acc[val] = (acc[val] || []).concat(arr[i]);
    return acc;
  }, {});

export default class WaveformFigure extends Component {

  state = {
    figure: null,
    deviceId: getQueryString('id')
  };

  componentDidMount() {
    getDeviceOutdoorFireHydrantCurrent({deviceId: this.state.deviceId}).then(data => {
      let dataX = [];
      const color = ['#49a1ff', '#49a1ff', '#49a1ff', '#49a1ff', '#49a1ff', '#49a1ff', '#49a1ff', '#49a1ff']
      const ans = groupBy(flatten(data.map(it => 
        Object.keys(it.valueMap)
              .filter(v => v.indexOf("pressure") === 0)
              .map(u => ({key: u, value: it.valueMap[u]}))
      )), 'key')
      
      dataX = data.map(item => item.createTime);

      const v = Object.values(ans).map((it:Array<{value: string}>, index) => ({
        name:`水压${index+1}`,
        type:'line',
        areaStyle: {},
        color: '#49a1ff',
        data: it.map(u => u.value)
      }))
      
      SingleFigure({
        ref: this.state.figure,
        color,
        dataX,
        data: v
      })
    });
  }

  render() {
    return (
      <div>
        <div ref={(value) => this.state.figure = value} style={{'height': '400px'}}></div>
      </div>
    )
  }
}
